package cn.org.spring.wechar.controller;


import cn.org.spring.wechar.config.BasicInfo;
import cn.org.spring.wechar.config.WeCharConfig;
import cn.org.spring.wechar.entity.WeChatUser;
import cn.org.spring.wechar.utils.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author： 谢辉
 * @date： 2021/5/8
 * @email: xieh_mail@163.com
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Slf4j
@Controller
public class IndexController {
    @Autowired
    WeCharConfig charConfig;
    @Autowired
    CacheUtil cacheUtil;
    @Autowired
    BasicInfo basicInfo;

    @RequestMapping("/index")
    public String index(@RequestParam(value = "userid", required = false) String userid,
                        @CookieValue(value = "wechat-token", required = false) String wechatToken,
                        HttpServletResponse response,
                        Model model) throws IOException {
        // 转到登录页
        if (StringUtils.isEmpty(userid) && StringUtils.isEmpty(wechatToken)) {
            return "forward:/login";
        }
        String key = "";
        if (!StringUtils.isEmpty(userid)) {
            key = userid;
        } else if (!StringUtils.isEmpty(wechatToken)) {
            key = wechatToken;
        }
        Object o = cacheUtil.get("wechatuser:" + key);
        if (null != o) {
            WeChatUser weChatUser = (WeChatUser) o;
            model.addAttribute("user", weChatUser);
            response.addCookie(new Cookie("wechat-token", userid));
            return "index";
        } else {
            return "forward:/login";
        }

    }


    @RequestMapping("/login")
    public String login(Model model) throws IOException {
        /*String content = WeCharConstant.OAUTH2_AUTHORIZE.replace("APPID", charConfig.getAppId())
                .replace("REDIRECT_URI", basicInfo.getUrlPrefix() + "/v1/weChar/getCode").replace("SCOPE", "snsapi_userinfo");
        log.info("登录链接：【{}】", content);
        model.addAttribute("url", content);*/
        return "login";
    }

    @RequestMapping("/view/recharge")
    public String recharge(Model model) {
        return "recharge";
    }


}
